package ch.dungegondefenders;

import java.util.ArrayList;
import java.util.List;

import javafx.animation.PathTransition;
import javafx.animation.Timeline;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Path;
import javafx.scene.shape.Shape;
import javafx.util.Duration;

public abstract class MovingElement {

	private Group root;
	private int x;
	private int y;
	private int width;
	private int height;
	private Shape shape;
	private Path path;
	private PathTransition pTrans;
	@SuppressWarnings("rawtypes")
	private List<EventHandler> handlers = new ArrayList<EventHandler>();

	public MovingElement(Group root, Shape shape) {
		this.root = root;
		setShape(shape);
		initHandlers();
	}

	public MovingElement(Group root, Shape shape, int x, int y, int width,
			int height) {
		this(root, shape);
		setPosition(x, y);
		setDimension(width, height);
	}

	public void setPosition(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public void setDimension(int width, int height) {
		this.width = width;
		this.height = height;
	}

	public void setShape(Shape shape) {
		this.shape = shape;
	}

	public void setPath(Path path) {
		this.path = path;
	}

	public abstract void keyHooks(final KeyEvent keyEvent);

	public abstract void mouseHooks(final MouseEvent mouseEvent);

	public void addHandler(@SuppressWarnings("rawtypes") EventHandler handler) {
		handlers.add(handler);
	}

	public void move() {
		if (path != null) {
			pTrans = new PathTransition();
			pTrans.setDuration(Duration.INDEFINITE);
			pTrans.setPath(path);
			pTrans.setNode(shape);
			pTrans.setCycleCount(Timeline.INDEFINITE);
			pTrans.play();

			// Path path = new Path();
			// path.getElements().add(new MoveTo(20,20));
			// path.getElements().add(new CubicCurveTo(380, 0, 380, 120, 200,
			// 120));
			// path.getElements().add(new CubicCurveTo(0, 120, 0, 240, 380,
			// 240));
			// pathTransition.setOrientation(PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT);
			// pathTransition.setAutoReverse(true);
			// pathTransition.play();

		}
	}

	public void stop() {
		if (path != null) {
			if (pTrans != null) {
				pTrans.stop();
			}
		}
	}

	private void initHandlers() {
		EventHandler<KeyEvent> keyEventHandler = new EventHandler<KeyEvent>() {
			public void handle(final KeyEvent keyEvent) {
				keyHooks(keyEvent);
			}
		};

		handlers.add(keyEventHandler);

		EventHandler<MouseEvent> mouseEventHandler = new EventHandler<MouseEvent>() {

			@Override
			public void handle(MouseEvent mouseEvent) {
				mouseHooks(mouseEvent);
			}
		};

		handlers.add(mouseEventHandler);
	}

}
